//
//  WBNetworkManager.swift
//  新浪微博
//
//  Created by shanlin on 2017/8/24.
//  Copyright © 2017年 shanlin. All rights reserved.
//

import UIKit
import AFNetworking

//Swift的枚举支持任意数据类型
//swith / enum 在 oc中只是支持整数

enum WBHTTPMethod {
    case GET
    case POST

}

class WBNetworkManager: AFHTTPSessionManager {
    //静态区  / 常量  / 闭包 /在第一次访问时,执行闭包,并且将结果保存在 shared 常量中
    static let shared = WBNetworkManager()
    
    //访问令牌.所有的访问请求都基于此令牌(登录除外)
    var accessToken : String? = "2.00jALrBD0TCW2E6eea5b7bfcsjmz1E"
    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters:[String : AnyObject], completion:@escaping (_ json:AnyObject?, _ isSuccess:Bool)->()) {
        
        //0 判断token是否为nil 
        guard let token = accessToken else {
            //TODO: 发送通知 ,提示用户登录
            //FIXME: 发送通知 ,提示用户登录
            print("没有token,需要登录")
            completion(nil, false)
            return
        }
        
        //处理token字典
        var parameters = parameters
        
        //1>判断 参数字典是否存在, 如果为nil,应该新建一个字典
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        //2>设置参数字典
        parameters["access_token"] = token as AnyObject
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters:[String : AnyObject], completion:@escaping (_ json:AnyObject?, _ isSuccess:Bool)->()) {
        ///成功回调
        let successCallBack = {(task:URLSessionDataTask, json:Any)->() in
            completion(json as AnyObject, true)
        }
        ///失败回调
        let failureCallBack = {(task:URLSessionDataTask?, error: NSError)->() in
            print("网络请求错误\(error)")
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                //FIXME: 发送通知(本方法不知道谁调用,谁接收到通知, 谁处理)
            }
        }
        
        
        /// Cannot convert value of type '(URLSessionTask, AnyObject?) -> ()' to expected argument type '((URLSessionDataTask, Any?) -> Void)?'
        
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
        }
    }
    
    
    
    
    

    
    
}
 
 
